<template>
	<view class="view-contain">
		<!-- 公共模块，显示返回箭头和标题 -->
		<public-module leftIcon="arrow-left" :title="title" />

		<!-- 打卡内容区域，包含日历和输入框 -->
		<view class="punch-content" :style="{ height: `${height}px` }">
			<!-- 年月选择器和总结按钮 -->
			<view class="date-selector-container">
				<view class="date-selector">
					<picker mode="selector" :range="years" :value="yearIndex" @change="onYearChange">
						<view class="selector-view">{{ currentYear }}年</view>
					</picker>
					<picker mode="selector" :range="months" :value="monthIndex" @change="onMonthChange">
						<view class="selector-view">{{ currentMonth }}月</view>
					</picker>
				</view>
				<view class="summary-btn" @click="toggleMonthlySummary">
					总结该月
				</view>
			</view>

			<!-- 日历部分 -->
			<view class="punch-calendar" v-show="todayPunchContent && !showMonthlySummary">
				<!-- 日历头部显示星期几 -->
				<view class="calendar-header">
					<view v-for="(day, index) in ['日', '一', '二', '三', '四', '五', '六']" :key="index">
						{{ day }}
					</view>
				</view>
				<!-- 日历主体 -->
				<view class="calendar-body">
					<view v-for="(day, index) in calendarDays" :key="index" class="calendar-day"
						:class="{ 'punch-day': isPunched(day), 'gray-day': isOtherMonth(day) }"
						@click="handleDayClick(day)">
						{{ isPunched(day) ? '√' : day.getDate() }}
					</view>
				</view>
			</view>

			<!-- 月度总结区域 - 调整为靠左对齐 -->
			<view class="monthly-summary" v-if="showMonthlySummary">
				<view class="summary-title">月度学习总结</view>
				<view class="summary-content">
					<view class="summary-item">本月应打卡：{{ monthlySummary.daysInMonth }}天</view>
					<view class="summary-item">实际打卡：{{ monthlySummary.actualPunchDays }}天</view>
					<view class="summary-item">完成率：{{ monthlySummary.completionRate }}%</view>
					<view class="summary-divider"></view>
					<view class="summary-item">计划做题总数：{{ monthlySummary.totalPlannedQuestions }}道</view>
					<view class="summary-item">实际做题数：{{ monthlySummary.totalActualQuestions }}道</view>
					<view class="summary-item">做题完成率：{{ monthlySummary.questionsCompletionRate }}%</view>
					<view class="summary-divider"></view>
					<view class="summary-item">计划学习总时长：{{ monthlySummary.totalPlannedDuration }}分钟</view>
					<view class="summary-item">实际学习总时长：{{ monthlySummary.totalActualDuration }}分钟</view>
					<view class="summary-item">学习时长完成率：{{ monthlySummary.durationCompletionRate }}%</view>
				</view>
			</view>

			<!-- 新增选中日期内容显示区域 -->
			<view class="today-punch-content" v-if="selectedDayContent && !showMonthlySummary">
				<view class="content-section yesterday-section">
					<view class="content-title">昨日回顾</view>
					<view class="study-content">{{ selectedDayYesterdayStudyContent }}</view>
					<view class="input-row">
						<view class="content-text">
							实际用时{{ selectedDayYesterdayStudyDuration }}min,
						</view>
						<view class="content-text">
							实际刷题{{ selectedDayYesterdayQuestionCount }}道
						</view>
					</view>
				</view>

				<view class="content-section today-section">
					<view class="content-title">今日计划</view>
					<view class="study-content">{{ selectedDayContent }}</view>
					<view class="input-row">
						<view class="content-text">
							预计用时{{ selectedDayExpectedDuration }}min,
						</view>
						<view class="content-text">
							预计刷题{{ selectedDayExpectedQuestionCount }}道
						</view>
					</view>
					<view class="content-time">{{ selectedDayTime }}</view>
				</view>
			</view>

			<!-- 打卡输入框 -->
			<view class="punch-input-wrapper" v-if="!todayPunchContent && !showMonthlySummary">
				<view class="punch-input-container">
					

					<!-- 昨日回顾任务列表 -->
					<view class="content-section yesterday-section">
						<view class="section-header">
							<view class="content-title">昨日回顾</view>
							<view class="add-task-btn" @click="addYesterdayTask">+ 新增任务</view>
						</view>
						<view class="task-container">
							<view v-for="(task, index) in yesterdayTasks" :key="index" class="task-item">
								<!-- 任务内容输入框 -->
								<view class="task-input-row">
									<input class="task-input" type="text" v-model="task.content" placeholder="请输入昨日学习任务"
										@focus="handleInputFocus" @input="updateYesterdayStudyContent" />
									<view class="delete-btn" v-show="yesterdayTasks.length > 1" @click="deleteYesterdayTask(index)">
										×
									</view>
								</view>
								<!-- 任务实际数据输入框 -->
								<view class="task-plan-row">
									<view class="plan-input-group">
										<text class="plan-label">实际用时：</text>
										<input class="plan-input-with-label" type="number" v-model="task.actualDuration"
											placeholder="分钟*" @focus="handleInputFocus" @input="updateYesterdayStudyContent" />
									</view>
									<view class="plan-input-group">
										<text class="plan-label">实际刷题：</text>
										<input class="plan-input-with-label" type="number" v-model="task.actualQuestions"
											placeholder="道*" @focus="handleInputFocus" @input="updateYesterdayStudyContent" />
									</view>
								</view>
							</view>
						</view>
						
						<!-- 显示累加后的实际学习时长和刷题量 -->
						<view class="summary-row" v-show="yesterdayTasks.length > 0">
							<view class="summary-text">总实际用时：{{ totalActualDuration }}分钟</view>
							<view class="summary-text">总实际刷题：{{ totalActualQuestions }}道</view>
						</view>
						

					</view>



					<!-- 今日计划任务输入框 -->
					<view class="content-section today-section">
						<view class="section-header">
							<view class="content-title">今日计划</view>
							<view class="add-task-btn" @click="addTask">+ 新增学习任务</view>
						</view>
						<view class="task-container">
							<view v-for="(task, index) in todayTasks" :key="index" class="task-item">
								<!-- 任务内容输入框 -->
								<view class="task-input-row">
									<input class="task-input" type="text" v-model="task.content" placeholder="请输入学习任务"
										@focus="handleInputFocus" />
									<view class="delete-btn" v-show="todayTasks.length > 1" @click="deleteTask(index)">
										×
									</view>
								</view>
								<!-- 任务计划输入框 -->
								<view class="task-plan-row">
									<input class="plan-input" type="number" v-model="task.plannedDuration"
										placeholder="计划用时(分钟)*" @focus="handleInputFocus" />
									<input class="plan-input" type="number" v-model="task.plannedQuestions"
										placeholder="计划刷题量*" @focus="handleInputFocus" />
								</view>
							</view>
						</view>

						<!-- 显示累加后的预计学习时长和刷题量 -->
						<view class="summary-row">
							<view class="summary-text">总计划用时：{{ totalPlannedDuration }}分钟</view>
							<view class="summary-text">总计划刷题：{{ totalPlannedQuestions }}道</view>
						</view>
					</view>

					<view class="punch-btn-row">
						<view class="punch-send-btn" @click="submitPunch">
							<text>发送</text>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex';
	import {
		markAdd,
		markList,
		msgSecCheck
	} from '@/config/api.js';
	import { parseDate } from '@/config/utils.js';

	export default {
		data() {
			return {
				title: '打卡日历',
				height: 0,
				studyContent: '',
				todayExpectedDuration: '',
				todayExpectedQuestionCount: '',
				yesterdayCompletionRate: '',
				yesterdayStudyContent: '昨日未打卡',
				yesterdayStudyDuration: '',
				yesterdayQuestionCount: '',
				showPunchModal: true,
				currentYear: new Date().getFullYear(),
				currentMonth: new Date().getMonth() + 1,
				years: [], // 年份选择列表
				months: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], // 月份选择列表
				yearIndex: 0, // 当前选中的年份索引
				monthIndex: 0, // 当前选中的月份索引
				punchRecords: [],
				calendarDays: [],
				todayPunchContent: '',
				todayPunchTime: '',
				selectedDayContent: '',
				selectedDayTime: '',
				selectedDayExpectedDuration: '',
				selectedDayExpectedQuestionCount: '',
				selectedDayYesterdayCompletionRate: '',
				selectedDayYesterdayStudyContent: '',
				selectedDayYesterdayStudyDuration: '',
				selectedDayYesterdayQuestionCount: '',
				inputFocused: false,
				scrollTop: 0,
				keyboardHeight: 0,
				isIOS: false,
				focusedElementId: '',
				todayTasks: [{
					content: '',
					plannedDuration: '', // 计划用时（分钟）
					plannedQuestions: '' // 计划刷题量
				}], // 今日任务列表，默认一个空任务
				yesterdayTasks: [], // 解析后的昨日任务列表（包含内容、实际用时、实际做题量）
				yesterdayRecord: false, // 标记是否有昨日打卡记录
				showMonthlySummary: false, // 控制月度总结显示/隐藏
				monthlySummary: { // 月度总结数据
					daysInMonth: 0,
					actualPunchDays: 0,
					completionRate: 0,
					totalPlannedQuestions: 0,
					totalActualQuestions: 0,
					questionsCompletionRate: 0,
					totalPlannedDuration: 0,
					totalActualDuration: 0,
					durationCompletionRate: 0
				}
			};
		},

		onLoad() {
			// 获取系统信息并设置高度
			const res = uni.getWindowInfo();
			this.height = res.windowHeight;
			this.isIOS = res.platform === 'ios';

			// 初始化年份选择列表（当前年份前5年）
			const currentYear = new Date().getFullYear();
			for (let i = currentYear - 5; i <= currentYear; i++) {
				this.years.push(i);
			}
			// 设置当前年份和月份的索引
			this.yearIndex = this.years.indexOf(currentYear);
			this.monthIndex = this.currentMonth - 1;

			// 初始化日历
			this.initCalendar();
			// 获取打卡记录
			this.getPunchRecords();

			// 监听键盘事件
			uni.onKeyboardHeightChange(res => {
				this.keyboardHeight = res.height;

				if (res.height === 0) {
					// 键盘收起
					this.inputFocused = false;
					this.focusedElementId = '';
					// 恢复滚动位置
					this.$nextTick(() => {
						uni.pageScrollTo({
							scrollTop: this.scrollTop,
							duration: 300
						});
					});
				} else {
					// 键盘弹出
					this.inputFocused = true;
					// 保存当前滚动位置
					uni.getSystemInfo({
						success: (sysInfo) => {
							this.adjustForKeyboard();
						}
					});
				}
			});
		},

		onUnload() {
			// 页面卸载时取消监听
			uni.offKeyboardHeightChange();
		},

		computed: {
			...mapState(['user', 'loginSuccess']),
			
			// 计算总的预计学习时长（累加所有任务的计划用时）
			totalPlannedDuration() {
				return this.todayTasks.reduce((total, task) => {
					const duration = parseInt(task.plannedDuration) || 0;
					return total + duration;
				}, 0);
			},
			
			// 计算总的预计刷题量（累加所有任务的计划刷题量）
			totalPlannedQuestions() {
				return this.todayTasks.reduce((total, task) => {
					const questions = parseInt(task.plannedQuestions) || 0;
					return total + questions;
				}, 0);
			},
			
			// 计算昨日总实际学习时长（累加所有任务的实际用时）
			totalActualDuration() {
				return this.yesterdayTasks.reduce((total, task) => {
					const duration = parseInt(task.actualDuration) || 0;
					return total + duration;
				}, 0);
			},
			
			// 计算昨日总实际刷题量（累加所有任务的实际做题量）
			totalActualQuestions() {
				return this.yesterdayTasks.reduce((total, task) => {
					const questions = parseInt(task.actualQuestions) || 0;
					return total + questions;
				}, 0);
			}
		},

		methods: {
			// 年份选择变化
			onYearChange(e) {
				const index = e.detail.value;
				this.currentYear = this.years[index];
				this.yearIndex = index;
				this.initCalendar();
				// 如果正在显示总结，重新计算
				if (this.showMonthlySummary) {
					this.calculateMonthlySummary();
				}
			},
			
			// 月份选择变化
			onMonthChange(e) {
				const index = e.detail.value;
				this.currentMonth = this.months[index];
				this.monthIndex = index;
				this.initCalendar();
				// 如果正在显示总结，重新计算
				if (this.showMonthlySummary) {
					this.calculateMonthlySummary();
				}
			},

			// 获取打卡记录
			async getPunchRecords() {
				try {
					uni.showLoading({
						title: '加载打卡记录...'
					});
					const res = await markList();
					if (res.code === 200) {
						this.punchRecords = res.data;

						// 获取昨天的日期
						const yesterday = new Date();
						yesterday.setDate(yesterday.getDate() - 1);

						// 查找昨天的打卡记录
						const yesterdayRecord = res.data.find(item => {
							const recordDate = parseDate(item.studyMarkDate);
							return (
								recordDate.getDate() === yesterday.getDate() &&
								recordDate.getMonth() === yesterday.getMonth() &&
								recordDate.getFullYear() === yesterday.getFullYear()
							);
						});

						// 标记是否有昨日记录
						this.yesterdayRecord = !!yesterdayRecord;

						// 如果找到昨天的记录，填充学习内容
						if (yesterdayRecord) {
							this.yesterdayStudyContent = yesterdayRecord.studyContent;
							// 解析昨日学习内容为任务数组
							this.parseYesterdayContent();
						} else {
							// 无昨日记录时，重置数据为默认值，并提供一个空任务供用户填写
							this.yesterdayStudyContent = '昨日未打卡';
							this.yesterdayTasks = [{
								content: '',
								actualDuration: '',
								actualQuestions: ''
							}]; // 提供一个空任务供用户填写
							this.yesterdayCompletionRate = '';
							this.yesterdayStudyDuration = '';
							this.yesterdayQuestionCount = '';
						}

						// 获取今天的打卡内容
						const today = new Date();
						const todayRecord = res.data.find(item => {
							const recordDate = parseDate(item.studyMarkDate);
							return (
								recordDate.getDate() === today.getDate() &&
								recordDate.getMonth() === today.getMonth() &&
								recordDate.getFullYear() === today.getFullYear()
							);
						});
						this.todayPunchContent = todayRecord ? todayRecord.studyContent : '';
						this.selectedDayContent = todayRecord ? todayRecord.studyContent : '';
						this.selectedDayTime = todayRecord ? todayRecord.studyMarkDate : '';
						this.selectedDayExpectedDuration = todayRecord ? todayRecord.todayExpectedDuration : '';
						this.selectedDayExpectedQuestionCount = todayRecord ? todayRecord.todayExpectedQuestionCount :
							'';
						this.selectedDayYesterdayCompletionRate = todayRecord ? todayRecord.yesterdayCompletionRate :
							'';
						this.selectedDayYesterdayStudyContent = todayRecord ? todayRecord.yesterdayStudyContent : '';
						this.selectedDayYesterdayStudyDuration = todayRecord ? todayRecord.yesterdayStudyDuration : '';
						this.selectedDayYesterdayQuestionCount = todayRecord ? todayRecord.yesterdayQuestionCount : '';
						
						// 重新初始化日历以更新打卡状态
						this.initCalendar();
						
						// 如果正在显示总结，重新计算
						if (this.showMonthlySummary) {
							this.calculateMonthlySummary();
						}
					}
					uni.hideLoading();
				} catch (err) {
					uni.hideLoading();
					console.error('获取打卡记录失败', err);
				}
			},

			// 初始化日历 - 修复上月剩余天数显示顺序
			initCalendar() {
				const firstDay = new Date(this.currentYear, this.currentMonth - 1, 1);
				const firstDayOfWeek = firstDay.getDay(); // 当月第一天是星期几（0-6）
				const lastDay = new Date(this.currentYear, this.currentMonth, 0);
				const daysInMonth = lastDay.getDate();

				// 保存当月天数用于月度总结
				this.monthlySummary.daysInMonth = daysInMonth;

				this.calendarDays = [];

				// 修复：填充上月剩余天数，按正确顺序显示
				const prevMonth = this.currentMonth - 2; // 上月的月份索引
				const prevMonthLastDate = new Date(this.currentYear, this.currentMonth - 1, 0).getDate(); // 上月最后一天
				
				// 从需要显示的第一天开始到上月最后一天
				for (let i = 1; i <= firstDayOfWeek; i++) {
					const day = prevMonthLastDate - firstDayOfWeek + i;
					this.calendarDays.push(new Date(this.currentYear, prevMonth, day));
				}

				// 填充本月天数
				for (let i = 1; i <= daysInMonth; i++) {
					this.calendarDays.push(new Date(this.currentYear, this.currentMonth - 1, i));
				}

				// 填充下月开始天数 - 只填充到需要的天数
				const totalCells = Math.ceil(this.calendarDays.length / 7) * 7;
				const remainingDays = totalCells - this.calendarDays.length;
				for (let i = 1; i <= remainingDays; i++) {
					this.calendarDays.push(new Date(this.currentYear, this.currentMonth, i));
				}
			},

			// 判断某一天是否打卡
			isPunched(day) {
				return this.punchRecords.some(record => {
					const recordDate = parseDate(record.studyMarkDate);
					return (
						recordDate.getDate() === day.getDate() &&
						recordDate.getMonth() === day.getMonth() &&
						recordDate.getFullYear() === day.getFullYear()
					);
				});
			},

			// 判断是否为上月或下月日期
			isOtherMonth(day) {
				return day.getMonth() !== this.currentMonth - 1;
			},

			// 新增任务
			addTask() {
				this.todayTasks.push({
					content: '',
					plannedDuration: '',
					plannedQuestions: ''
				});
			},

			// 删除任务
			deleteTask(index) {
				if (this.todayTasks.length > 1) {
					this.todayTasks.splice(index, 1);
				}
			},
			
			// 新增昨日任务
			addYesterdayTask() {
				this.yesterdayTasks.push({
					content: '',
					actualDuration: '',
					actualQuestions: ''
				});
				this.updateYesterdayStudyContent();
			},

			// 删除昨日任务
			deleteYesterdayTask(index) {
				if (this.yesterdayTasks.length > 1) {
					this.yesterdayTasks.splice(index, 1);
					this.updateYesterdayStudyContent();
				}
			},

			// 解析昨日学习内容为任务数组（包含内容、实际用时、实际做题量）
			parseYesterdayContent() {
				if (!this.yesterdayStudyContent || this.yesterdayStudyContent === '昨日未打卡') {
					this.yesterdayTasks = [];
					return;
				}

				const lines = this.yesterdayStudyContent.split('\n').map(line => line.trim()).filter(line => line);
				this.yesterdayTasks = lines.map((line, index) => {
					// 匹配"实际"格式：序号. 任务内容，实际Xmin，实际X道
					const actualFormatMatch = line.match(/^(\d+)\. (.+?)，实际(\d+)min，实际(\d+)道$/);
					if (actualFormatMatch) {
						return {
							content: actualFormatMatch[2].trim(),
							actualDuration: actualFormatMatch[3],
							actualQuestions: actualFormatMatch[4]
						};
					}
					
					// 匹配新格式：序号. 任务内容（计划用时Xmin，计划刷题X道）
					const newFormatMatch = line.match(/^(\d+)\. (.+)，计划(\d+)min，计划(\d+)道$/);
					if (newFormatMatch) {
						// 新格式：按照计划数据初始化实际数据
						return {
							content: newFormatMatch[2],
							actualDuration: newFormatMatch[3], // 用计划用时作为初始值
							actualQuestions: newFormatMatch[4] // 用计划刷题量作为初始值
						};
					}
					
					// 匹配"任务1，23min，2道"格式
					const simpleFormatMatch = line.match(/^(.+?)，(\d+)min，(\d+)道$/);
					if (simpleFormatMatch) {
						return {
							content: simpleFormatMatch[1].trim(),
							actualDuration: simpleFormatMatch[2],
							actualQuestions: simpleFormatMatch[3]
						};
					}
					
					// 匹配带"min"和"道"的格式，提取数字
					const minMatch = line.match(/(\d+)min/);
					const questionMatch = line.match(/(\d+)道/);
					
					// 提取任务内容（去除时间和题目数量信息）
					let content = line.replace(/^\d+\. /, '').replace('，完成', '').replace('，未完成', '').trim();
					content = content.replace(/，?\d+min/g, '').replace(/，?\d+道/g, '').trim();
					content = content.replace(/，$/, ''); // 去除末尾的逗号
					
					return {
						content: content || `任务${index + 1}`,
						actualDuration: minMatch ? minMatch[1] : '',
						actualQuestions: questionMatch ? questionMatch[1] : ''
					};
				});
			},

			// 更新昨日学习内容（不再自动添加序号，由formatTasksForSubmission统一处理）
			updateYesterdayStudyContent() {
				// 同步更新累计数据
				this.yesterdayStudyDuration = this.totalActualDuration;
				this.yesterdayQuestionCount = this.totalActualQuestions;
			},

			// 提交时将任务数组拼接为带状态的文本（保留兼容性）
			formatTasksForSubmission() {
				if (this.yesterdayTasks.length === 0) {
					return this.yesterdayStudyContent;
				}
				return this.yesterdayTasks
					.map((task, index) => {
						const taskNumber = index + 1;
						const content = task.content.trim();
						const duration = task.actualDuration || 0;
						const questions = task.actualQuestions || 0;
						return `${taskNumber}. ${content}，实际${duration}min，实际${questions}道`;
					})
					.join('\n');
			},

			// 发布学习内容
			async submitPunch() {
				// 验证任务是否为空
				const hasEmptyTask = this.todayTasks.some(task => !task.content.trim());
				if (hasEmptyTask) {
					uni.showToast({
						title: '请填写所有学习任务',
						icon: 'none',
						duration: 2000
					});
					return;
				}

				// 验证每个任务的计划用时和刷题量
				for (let i = 0; i < this.todayTasks.length; i++) {
					const task = this.todayTasks[i];
					if (!task.plannedDuration || task.plannedDuration <= 0) {
						uni.showToast({
							title: `请填写第${i + 1}个任务的计划用时`,
							icon: 'none',
							duration: 2000
						});
						return;
					}
					if (!task.plannedQuestions) {
						uni.showToast({
							title: `请填写第${i + 1}个任务的计划刷题量`,
							icon: 'none',
							duration: 2000
						});
						return;
					}
				}

				// 验证昨日任务是否为空（仅当有昨日记录时）
				if (this.yesterdayRecord && this.yesterdayTasks.length > 0) {
					const hasEmptyYesterdayTask = this.yesterdayTasks.some(task => !task.content.trim());
					if (hasEmptyYesterdayTask) {
						uni.showToast({
							title: '请填写所有昨日学习任务',
							icon: 'none',
							duration: 2000
						});
						return;
					}
					
					// 验证每个昨日任务的实际用时和做题量（必填项）
					for (let i = 0; i < this.yesterdayTasks.length; i++) {
						const task = this.yesterdayTasks[i];
						if (!task.actualDuration || task.actualDuration <= 0) {
							uni.showToast({
								title: `请填写第${i + 1}个昨日任务的实际用时`,
								icon: 'none',
								duration: 2000
							});
							return;
						}
						if (!task.actualQuestions || task.actualQuestions <= 0) {
							uni.showToast({
								title: `请填写第${i + 1}个昨日任务的实际做题量`,
								icon: 'none',
								duration: 2000
							});
							return;
						}
					}
				}
				
				// 如果没有昨日记录但用户添加了昨日任务，也需要验证
				if (!this.yesterdayRecord && this.yesterdayTasks.length > 0) {
					for (let i = 0; i < this.yesterdayTasks.length; i++) {
						const task = this.yesterdayTasks[i];
						if (task.content.trim()) { // 如果填写了任务内容
							if (!task.actualDuration || task.actualDuration <= 0) {
								uni.showToast({
									title: `请填写第${i + 1}个昨日任务的实际用时`,
									icon: 'none',
									duration: 2000
								});
								return;
							}
							if (!task.actualQuestions || task.actualQuestions <= 0) {
								uni.showToast({
									title: `请填写第${i + 1}个昨日任务的实际做题量`,
									icon: 'none',
									duration: 2000
								});
								return;
							}
						}
					}
				}

				if (this.user.nickName == "正备级") {
					uni.showToast({
						title: '请到【我的】-【个人信息】，修改昵称，昵称-备考城市-专业，如：小李-南京-计算机',
						icon: 'none',
						duration: 5000
					});
					return;
				}

				try {
					uni.showLoading({
						title: '发布中...',
						mask: true
					});

					// 处理任务数据（格式化为包含序号、内容、计划用时、计划刷题量的字符串）
					const studyContent = this.todayTasks.map((task, index) => {
						const taskNumber = index + 1;
						const content = task.content.trim();
						const duration = task.plannedDuration || 0;
						const questions = task.plannedQuestions || 0;
						return `${taskNumber}. ${content}，计划${duration}min，计划${questions}道`;
					}).join('\n');

					// 拼接带状态的昨日学习内容并更新累计数据
					this.yesterdayStudyContent = this.formatTasksForSubmission();
					
					// 确保昨日数据使用计算后的总值
					this.yesterdayStudyDuration = this.totalActualDuration;
					this.yesterdayQuestionCount = this.totalActualQuestions;

					const checkRes = await msgSecCheck({
						content: [studyContent, this.yesterdayStudyContent].filter(Boolean).join('\n')
					});
					if (checkRes.errcode !== 0) {
						return uni.$u.toast('内容包含违规信息，请修改');
					}

					const res = await markAdd({
						studyContent,
						todayExpectedDuration: this.totalPlannedDuration, // 使用计算出的总计划时长
						todayExpectedQuestionCount: this.totalPlannedQuestions, // 使用计算出的总计划刷题量
						yesterdayCompletionRate: this.yesterdayCompletionRate,
						yesterdayStudyContent: this.yesterdayStudyContent,
						yesterdayStudyDuration: this.yesterdayStudyDuration, // 使用累计的总实际用时
						yesterdayQuestionCount: this.yesterdayQuestionCount, // 使用累计的总实际刷题量
					});

					if (res.code === 200) {
						uni.hideLoading();
						uni.showToast({
							title: '打卡成功',
							icon: 'success',
							duration: 1500
						});
						// 重置今日任务
						this.todayTasks = [{
							content: '',
							plannedDuration: '',
							plannedQuestions: ''
						}];
						// 打卡成功后刷新打卡记录和日历
						await this.getPunchRecords();
					} else {
						throw new Error(res.message || '打卡失败');
					}
				} catch (err) {
					uni.hideLoading();
					console.error('打卡错误:', err);
					uni.showToast({
						title: err.message || '打卡失败',
						icon: 'none',
						duration: 2000
					});
				}
			},

			// 处理日期点击
			handleDayClick(day) {
				// 清空选中日期内容
				this.selectedDayContent = '';
				this.selectedDayTime = '';
				this.selectedDayExpectedDuration = '';
				this.selectedDayExpectedQuestionCount = '';
				this.selectedDayYesterdayCompletionRate = '';
				this.selectedDayYesterdayStudyContent = '';
				this.selectedDayYesterdayStudyDuration = '';
				this.selectedDayYesterdayQuestionCount = '';

				if (this.isPunched(day)) {
					// 从getPunchRecords获取的数据中查找记录
					const record = this.punchRecords.find(item => {
						const recordDate = parseDate(item.studyMarkDate);
						return (
							recordDate.getDate() === day.getDate() &&
							recordDate.getMonth() === day.getMonth() &&
							recordDate.getFullYear() === day.getFullYear()
						);
					});

					if (record) {
						this.selectedDayContent = record.studyContent;
						this.selectedDayTime = record.studyMarkDate;
						this.selectedDayExpectedDuration = record.todayExpectedDuration;
						this.selectedDayExpectedQuestionCount = record.todayExpectedQuestionCount;
						this.selectedDayYesterdayCompletionRate = record.yesterdayCompletionRate;
						this.selectedDayYesterdayStudyContent = record.yesterdayStudyContent;
						this.selectedDayYesterdayStudyDuration = record.yesterdayStudyDuration;
						this.selectedDayYesterdayQuestionCount = record.yesterdayQuestionCount;
					}
				} else {
					// 无打卡时显示提示
					uni.showToast({
						title: '该日期未打卡',
						icon: 'none',
						duration: 1500
					});
				}
			},

			// 处理输入框聚焦
			handleInputFocus(e) {
				this.inputFocused = true;
				this.focusedElementId = e.target.id;
				// 延迟执行，确保键盘完全弹出后再调整
				setTimeout(() => {
					this.adjustForKeyboard();
				}, 300);
			},

			// 调整页面以适应键盘
			adjustForKeyboard() {
				if (!this.inputFocused || this.keyboardHeight === 0) return;

				const that = this;
				// 获取当前聚焦的输入框位置
				uni.createSelectorQuery().select('.punch-input-container').boundingClientRect(rect => {
					if (rect) {
						// 计算输入框底部到视口底部的距离
						const bottomSpace = uni.getWindowInfo().windowHeight - rect.bottom;

						// 根据平台和键盘高度调整滚动距离
						let scrollDistance = 0;
						if (bottomSpace < this.keyboardHeight) {
							scrollDistance = this.keyboardHeight - bottomSpace + 60; // 额外增加60px间距

							// iOS可能需要更多调整
							if (this.isIOS) {
								scrollDistance += 40;
							}
						}

						// 执行滚动
						if (scrollDistance > 0) {
							uni.pageScrollTo({
								scrollTop: scrollDistance,
								duration: 300
							});
						}
					}
				}).exec();
			},
			
			// 切换月度总结显示/隐藏
			toggleMonthlySummary() {
				this.showMonthlySummary = !this.showMonthlySummary;
				if (this.showMonthlySummary) {
					this.calculateMonthlySummary();
				}
			},
			
			// 计算月度总结数据 - 累加该月所有打卡记录的相关数据
			calculateMonthlySummary() {
				// 筛选当前月份的打卡记录
				const currentMonthRecords = this.punchRecords.filter(record => {
					const recordDate = parseDate(record.studyMarkDate);
					return (
						recordDate.getMonth() === this.currentMonth - 1 &&
						recordDate.getFullYear() === this.currentYear
					);
				});
				
				// 计算实际打卡天数
				this.monthlySummary.actualPunchDays = currentMonthRecords.length;
				
				// 计算打卡完成率
				this.monthlySummary.completionRate = this.monthlySummary.daysInMonth 
					? Math.round((this.monthlySummary.actualPunchDays / this.monthlySummary.daysInMonth) * 100)
					: 0;
				
				// 累加计划和实际的做题总量
				this.monthlySummary.totalPlannedQuestions = currentMonthRecords.reduce((sum, record) => {
					return sum + (parseInt(record.todayExpectedQuestionCount) || 0);
				}, 0);
				
				this.monthlySummary.totalActualQuestions = currentMonthRecords.reduce((sum, record) => {
					return sum + (parseInt(record.yesterdayQuestionCount) || 0);
				}, 0);
				
				// 计算做题完成率
				this.monthlySummary.questionsCompletionRate = this.monthlySummary.totalPlannedQuestions > 0
					? Math.round((this.monthlySummary.totalActualQuestions / this.monthlySummary.totalPlannedQuestions) * 100)
					: 0;
				
				// 累加计划和实际的学习总时长
				this.monthlySummary.totalPlannedDuration = currentMonthRecords.reduce((sum, record) => {
					return sum + (parseInt(record.todayExpectedDuration) || 0);
				}, 0);
				
				this.monthlySummary.totalActualDuration = currentMonthRecords.reduce((sum, record) => {
					return sum + (parseInt(record.yesterdayStudyDuration) || 0);
				}, 0);
				
				// 计算学习时长完成率
				this.monthlySummary.durationCompletionRate = this.monthlySummary.totalPlannedDuration > 0
					? Math.round((this.monthlySummary.totalActualDuration / this.monthlySummary.totalPlannedDuration) * 100)
					: 0;
			}
		}
	};
</script>

<style>
	/* 全局容器样式 */
	.view-contain {
		display: flex;
		flex-direction: column;
		align-items: center;
		background-color: #f8f8f8;
		min-height: 100vh;
		padding-bottom: 5px;
		box-sizing: border-box;
	}

	/* 打卡内容区域样式 */
	.punch-content {
		width: 100%;
		height: 100%;
		background-color: #fff;
		display: flex;
		flex-direction: column;
		position: relative;
		overflow: auto;
	}

	/* 年月选择器容器 */
	.date-selector-container {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10px 15px;
		background-color: #f5f5f5;
	}

	/* 年月选择器样式 */
	.date-selector {
		display: flex;
		justify-content: flex-start;
		align-items: center;
	}

	.selector-view {
		padding: 5px 15px;
		font-size: 16px;
		color: #333;
		border: 1px solid #ddd;
		border-radius: 4px;
		background-color: #fff;
		margin: 0 5px;
	}

	/* 总结按钮样式 */
	.summary-btn {
		padding: 6px 15px;
		background-color: #4A89DC;
		color: white;
		border-radius: 4px;
		font-size: 14px;
		cursor: pointer;
	}

	.punch-calendar {
		padding: 15px;
	}

	.calendar-header {
		display: flex;
		justify-content: space-around;
		margin-top: 10px;
		font-size: 14px;
	}

	/* 日历主体样式 */
	.calendar-body {
		display: grid;
		grid-template-columns: repeat(7, 1fr);
		gap: 5px;
		justify-items: center;
		margin-bottom: 10px;
	}

	.calendar-day {
		text-align: center;
		padding: 0;
		border-radius: 50%;
		transition: background-color 0.3s ease;
		aspect-ratio: 1/1;
		display: flex;
		justify-content: center;
		align-items: center;
		width: 30px;
		height: 30px;
		font-size: 14px;
		line-height: 1;
		margin: 0 auto;
	}

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 15px;
	}

	.punch-day {
		background-color: #4A89DC;
		color: #fff;
		border-radius: 50%;
		width: 24px;
		height: 24px;
		display: flex;
		justify-content: center;
		align-items: center;
		margin: 3px;
	}

	/* 上月和下月日期灰色样式 */
	.gray-day {
		color: #ccc;
	}

	/* 打卡输入框样式 */
	.punch-input-wrapper {
		display: flex;
		flex-direction: column;
		gap: 10px;
		padding: 15px;
		flex: 1;
	}

	.punch-input-container {
		padding: 15px;
		border-top: 1px solid rgba(0, 0, 0, 0.1);
		position: relative;
		left: auto;
		right: auto;
		background-color: #fff;
		margin-bottom: 10px;
	}

	.punch-textarea {
		width: 100%;
		height: 80px;
		font-size: 14px;
		border: 1px solid rgba(0, 0, 0, 0.1);
		border-radius: 5px;
		padding: 10px;
		margin-bottom: 10px;
	}

	.punch-btn-row {
		display: flex;
		justify-content: space-between;
		gap: 10px;
	}

	.punch-send-btn {
		flex: 2;
		background-color: #4A89DC;
		color: #fff;
		padding: 8px 20px;
		border-radius: 15px;
		text-align: center;
	}

	.today-punch-content {
		padding: 15px;
		border-top: 1px solid rgba(0, 0, 0, 0.1);
	}

	.content-title {
		font-size: 16px;
		font-weight: bold;
		margin-bottom: 2px;
		color: #333;
		white-space: nowrap;
	}

	.content-text {
		font-size: 24px;
		line-height: 1.5;
	}

	.content-time {
		font-size: 12px;
		color: #999;
		margin-top: 5px;
		text-align: right;
	}

	.input-row {
		display: flex;
		gap: 10px;
		margin-bottom: 10px;
		align-items: center;
	}

	.number-input {
		flex: 1;
		height: 40px;
		border: 1px solid rgba(0, 0, 0, 0.1);
		border-radius: 5px;
		padding: 0 10px;
		font-size: 14px;
	}

	.content-section {
		padding: 5px;
		margin-bottom: 5px;
		border-radius: 8px;
	}

	.study-content {
		font-size: 16px;
		border-radius: 4px;
		margin: 10px 0;
		white-space: pre-line;
	}

	.content-text {
		font-size: 12px;
	}

	/* 新增键盘弹出时的样式 */
	.punch-input-wrapper.keyboard-open {
		transform: translateY(0);
	}

	/* 修复iOS键盘问题的特殊样式 */
	.ios-keyboard-fix {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		z-index: 100;
	}

	/* 新增任务输入框样式 */
	.task-container {
		display: flex;
		flex-direction: column;
		gap: 15px;
		margin: 10px 0;
	}

	.task-item {
		display: flex;
		flex-direction: column;
		gap: 8px;
		padding: 12px;
		border: 1px solid #e5e5e5;
		border-radius: 8px;
		background-color: #fafafa;
	}

	.task-input-row {
		display: flex;
		gap: 10px;
		align-items: center;
	}

	.task-input {
		flex: 1;
		height: 40px;
		border: 1px solid rgba(0, 0, 0, 0.1);
		border-radius: 5px;
		padding: 0 10px;
		font-size: 14px;
		background-color: #fff;
	}

	/* 新增：任务计划输入框样式 */
	.task-plan-row {
		display: flex;
		gap: 10px;
		margin-top: 5px;
		margin-bottom: 10px;
	}

	.plan-input {
		flex: 1;
		height: 35px;
		border: 1px solid rgba(0, 0, 0, 0.15);
		border-radius: 4px;
		padding: 0 8px;
		font-size: 13px;
		color: #666;
		background-color: #fff;
	}
	
	/* 新增：带标签的输入框样式 */
	.plan-input-group {
		flex: 1;
		display: flex;
		align-items: center;
		gap: 5px;
	}
	
	.plan-label {
		font-size: 13px;
		color: #666;
		white-space: nowrap;
		min-width: fit-content;
	}
	
	.plan-input-with-label {
		flex: 1;
		height: 35px;
		border: 1px solid rgba(0, 0, 0, 0.15);
		border-radius: 4px;
		padding: 0 8px;
		font-size: 13px;
		color: #666;
		background-color: #fff;
	}

	/* 新增：总计显示样式 */
	.summary-row {
		display: flex;
		justify-content: space-between;
		padding: 10px 15px;
		background-color: #f0f8ff;
		border: 1px solid #e1f0ff;
		border-radius: 6px;
		margin: 10px 0;
	}

	.summary-text {
		font-size: 14px;
		color: #4a89dc;
		font-weight: 500;
	}

	.delete-btn {
		color: #ff4d4f;
		font-size: 18px;
		cursor: pointer;
		padding: 5px;
		min-width: 20px;
		text-align: center;
	}

	.add-task-btn {
		color: #4a89dc;
		font-size: 14px;
		text-align: right;
		cursor: pointer;
		padding-top: 5px;
	}

	/* 状态按钮样式 */
	.status-btn {
		padding: 8px 12px;
		border: 1px solid #e5e5e5;
		border-radius: 4px;
		font-size: 14px;
		cursor: pointer;
		white-space: nowrap;
	}

	.status-btn:hover {
		background-color: #f8f8f8;
	}

	.status-btn.completed {
		color: #4cd964;
		/* 绿色 */
	}

	.status-btn.uncompleted {
		color: #ff4d4f;
		/* 红色 */
	}



	/* 月度总结样式 - 调整为靠左对齐 */
	.monthly-summary {
		padding: 15px;
		border-top: 1px solid rgba(0, 0, 0, 0.1);
	}

	.summary-title {
		font-size: 18px;
		font-weight: bold;
		margin-bottom: 20px;
		color: #333;
	}

	.summary-content {
		display: flex;
		flex-direction: column;
		gap: 12px;
	}

	.summary-item {
		font-size: 16px;
		color: #555;
		line-height: 1.5;
		text-align: left; /* 内容项靠左对齐 */
	}

	.summary-divider {
		height: 1px;
		background-color: #eee;
		margin: 10px 0;
	}
</style>
